package hy;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.CountDownLatch;

public class SuperSell {
    public static void main(String[] args)throws Exception {
        final JedisPool pool=Util.getInstance();
        Jedis j=pool.getResource();
        j.set("count","10");
        j.ltrim("orders",-1,0);
        CountDownLatch cd=new CountDownLatch(1000);
        for(int i=0;i<1000;i++){
            new Thread(i+"号客户"){
                @Override
                public void run() {
                    try (Jedis j = pool.getResource()) {//这是jdk8新特性，可以自动关闭资源
                        long count=Long.valueOf(j.get("count"));
                        if(count<=0){
                            System.out.println("没有商品，直接退出");
                            return;
                        }
                        count=j.decr("count");//注意：这里是单线程
                        if(count>=0){
                            j.rpush("orders",Thread.currentThread().getName());
                        }else{
                            System.out.println("虽然成功减了库存，但还是买不着！！！");
                        }
                    }finally {
                        cd.countDown();
                    }
                }
            }.start();
        }
        cd.await();
        System.out.println(j.lrange("orders",0,-1));
        j.close();
    }
}
